#include "MyGlWindow.h"
#include <QOpenGLExtraFunctions>
#include <QTime>
#include <QDebug>


#define MY_GL_FUNC  context()->extraFunctions()


void MyGlWindow::initializeGL()
{
    if (! MY_GL_FUNC) {
        qCritical("NO support for QOpenGLExtraFunctions!");
        ::exit(0);
    }

    MY_GL_FUNC->initializeOpenGLFunctions();
    printContextInformation();

    connect(this, SIGNAL(frameSwapped()), SLOT(update()));
}

void MyGlWindow::paintGL()
{
    static GLfloat color[] = {0.0f, 0.8f, 1.0f, 1.0f};
    static bool flag = true;

    static int last_msec = QTime::currentTime().msec();
    int msec = QTime::currentTime().msec();

    if (msec < last_msec)
        flag = ! flag;

    int value = flag ? msec : 999 - msec;

    color[2] = value / 1000.0f;
    color[1] = color[2] * 0.8f;

    MY_GL_FUNC->glClearBufferfv(GL_COLOR, 0, color);
    last_msec = msec;
}

void MyGlWindow::printContextInformation()
{
  QString glType;
  QString glVersion;
  QString glProfile;

  // Get Version Information
  glType = (context()->isOpenGLES()) ? "OpenGL ES" : "OpenGL";
  glVersion = reinterpret_cast<const char*>(MY_GL_FUNC->glGetString(GL_VERSION));

  // Get Profile Information
#define CASE(c) case QSurfaceFormat::c: glProfile = #c; break
  switch (format().profile())
  {
    CASE(NoProfile);
    CASE(CoreProfile);
    CASE(CompatibilityProfile);
  }
#undef CASE

  // qPrintable() will print our QString w/o quotes around it.
  qDebug() << qPrintable(glType) << qPrintable(glVersion)
           << "(" << qPrintable(glProfile) << ") " << format().swapBehavior()
           << " swapInterval " << format().swapInterval();
}
